﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace AisinGioro.Notify
{
    /// <summary>
    /// Telegram 通知类
    /// </summary>
    public class TelegramNotify : NotifyBase
    {
        private static readonly HttpClient _hc;
        private TelegramNotifyOption _option;

        static TelegramNotify()
        {
            _hc = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true });
            _hc.MaxResponseContentBufferSize = 1024 * 1024; //1MB
            _hc.DefaultRequestHeaders.Add("user-agent", "Jaguar");
            _hc.Timeout = new TimeSpan(0, 1, 0); //1 minute
        }
                
        [ConfigurationProperty("option", IsRequired = true)]
        protected TelegramNotifyOption Option
        {
            get
            {
                if (_option == null)
                    _option = (TelegramNotifyOption)this["option"];
                
                return _option;
            }
        }

        public override async Task<string> SendMsg(string message)
        {
            if (!this.Enabled)
                return await Task.FromResult<string>(null);
            
            string url = string.Format("https://api.telegram.org/bot{0}/sendMessage", this.Option.Token);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            IDictionary<string, string> content = new Dictionary<string, string>
            {
                { "chat_id", this.Option.ChatId },
                { "text", message }
            };
            HttpContent httpContent = new FormUrlEncodedContent(content);
            var response = await _hc.PostAsync(url, httpContent);
            response.EnsureSuccessStatusCode();
            var result = await response.Content.ReadAsStringAsync();

            return result;
        }
    }

    public class TelegramNotifyOption : ConfigurationElement
    {
        private string _token = null;
        private string _chatId = null;

        [ConfigurationProperty("token", IsRequired = true, IsKey = false)]
        public string Token
        {
            get
            {
                if (_token == null)
                    _token = this["token"].ToString();
                return _token;
            }
        }

        [ConfigurationProperty("chatId", IsRequired = true, IsKey = false)]
        public string ChatId
        {
            get
            {
                if (_chatId == null)
                    _chatId = this["chatId"].ToString();
                return _chatId;
            }
        }
    }
}
